"""
请假申请表模型
作者：资深Flask讲师
功能：员工请假申请、审批流程管理
"""

from datetime import datetime
from myflask.tools.bd import db


class LeaveRequest(db.Model):
    """
    请假申请表
    业务逻辑：
        1. 员工提交请假申请
        2. 自动分配给部门经理审批
        3. 超过3天需要HR二次审批（可扩展）
        4. 审批通过/拒绝后记录审批信息
    """
    __tablename__ = 'leave_requests'
    
    # 基本字段
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    
    # 申请人信息
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, comment='申请人ID')
    department_id = db.Column(db.Integer, db.ForeignKey('departments.id'), comment='申请人所属部门')
    
    # 请假信息
    leave_type = db.Column(db.String(20), nullable=False, comment='请假类型：sick病假/personal事假/annual年假/maternity产假/other其他')
    start_date = db.Column(db.Date, nullable=False, comment='开始日期')
    end_date = db.Column(db.Date, nullable=False, comment='结束日期')
    days = db.Column(db.Float, nullable=False, comment='请假天数（支持半天）')
    
    reason = db.Column(db.Text, comment='请假原因')
    
    # 审批信息
    status = db.Column(db.String(20), default='pending', comment='状态：pending待审批/approved已通过/rejected已拒绝/cancelled已取消')
    approver_id = db.Column(db.Integer, db.ForeignKey('users.id'), comment='审批人ID')
    approved_at = db.Column(db.DateTime, comment='审批时间')
    approval_comment = db.Column(db.String(500), comment='审批意见')
    
    # 时间戳
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    def to_dict(self):
        """转换为字典格式，便于JSON序列化"""
        # 导入放在函数内部，避免循环导入
        from myflask.models.user import User
        from myflask.models.department import Department
        
        # 获取关联数据
        applicant = User.query.get(self.user_id)
        department = Department.query.get(self.department_id) if self.department_id else None
        approver = User.query.get(self.approver_id) if self.approver_id else None
        
        # 请假类型映射
        leave_type_map = {
            'sick': '病假',
            'personal': '事假',
            'annual': '年假',
            'maternity': '产假',
            'other': '其他'
        }
        
        # 状态映射
        status_map = {
            'pending': '待审批',
            'approved': '已通过',
            'rejected': '已拒绝',
            'cancelled': '已取消'
        }
        
        return {
            'id': self.id,
            'user_id': self.user_id,
            'user_name': applicant.real_name or applicant.user if applicant else '未知',
            'user_account': applicant.user if applicant else '未知',
            'department_id': self.department_id,
            'department_name': department.name if department else '未分配',
            
            'leave_type': self.leave_type,
            'leave_type_name': leave_type_map.get(self.leave_type, self.leave_type),
            'start_date': self.start_date.strftime('%Y-%m-%d') if self.start_date else None,
            'end_date': self.end_date.strftime('%Y-%m-%d') if self.end_date else None,
            'days': float(self.days),
            'reason': self.reason,
            
            'status': self.status,
            'status_name': status_map.get(self.status, self.status),
            'approver_id': self.approver_id,
            'approver_name': approver.real_name or approver.user if approver else None,
            'approved_at': self.approved_at.strftime('%Y-%m-%d %H:%M:%S') if self.approved_at else None,
            'approval_comment': self.approval_comment,
            
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None,
        }
    
    def __repr__(self):
        return f'<LeaveRequest {self.id}: User({self.user_id}) {self.days}天 {self.status}>'

